//
//  SNReturnGoodsViewController.m
//  app
//
//  Created by 王少宁 on 15/5/15.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//  首次 申请售后

#import "SNReturnGoodsViewController.h"
#import "SNAddCommentsView.h"
#import "SNReturnGoodsView.h"
#import "HDActionSheetView.h"
#import "SNReturnGoodsDataManager.h"
#import "SNReturnGoodsRepetitiousViewController.h"

@interface SNReturnGoodsViewController ()<UITextViewDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (nonatomic, retain) UITextView * textView;
@property (nonatomic, retain) UIScrollView * myScrollView;
@property (nonatomic, retain) UILabel * placeLabel;
@property (nonatomic, retain) UIButton * addImgsBtn;
@property (nonatomic, retain) NSMutableArray * picBackGroundViewArray;
@property (nonatomic, retain) NSMutableArray * picArray;
@property (nonatomic, retain) SNReturnGoodsUpLoadPicDataManager * upLoadPicManager;
@property (nonatomic, retain) SNReturnGoodsDataManager * manager;
@property (nonatomic, retain) SNReturnGoodsUploadImgHttpResult * imgResut;
@property (nonatomic, retain) SNReturnGoodsUploadTextHttpResult * textResult;
@property (nonatomic, retain) UIButton * subMitBtn;
/** 键盘弹出时间*/
@property (nonatomic, assign) CGFloat kbTime;
@end

@implementation SNReturnGoodsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.picBackGroundViewArray = [[NSMutableArray alloc] init];
    self.picArray = [[NSMutableArray alloc] init];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationItem.title = @"申请售后";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardAppear:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardHidden:) name:UIKeyboardDidHideNotification object:nil];
    
    [self createView];
}

- (void)createView
{
    //提交按钮的背景图
    UIView * lowBackGroundView = CREATE_WITH_FRAME_OF(UIView, [self.view.ufo fx:0 fy:1.0 oy:-60],
                                                      [self.view.ubo ow:SCREEN_WIDTH oh:60]);
    [self.view addSubview:lowBackGroundView];
    
    //提交按钮
    _subMitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _subMitBtn.frame = CGRectOf([lowBackGroundView.ubo fx:0 ox:50 fy:0 oy:10],
                               [lowBackGroundView.ubo ow:SCREEN_WIDTH-100 oh:40]);
    UIImage * subMitBtnBackGroundImg = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"btnBackGround_gray@2x" ofType:@"png"]];
    subMitBtnBackGroundImg = [subMitBtnBackGroundImg resizableImageWithCapInsets:UIEdgeInsetsMake(UP(6), UP(6), UP(6), UP(6)) resizingMode:UIImageResizingModeStretch];
    [_subMitBtn setBackgroundImage:subMitBtnBackGroundImg forState:UIControlStateNormal];
    _subMitBtn.titleLabel.font = JKAppGlobleFontMenu;
    [_subMitBtn setTitle:@"提交申请" forState:UIControlStateNormal];
    [_subMitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_subMitBtn addTarget:self action:@selector(subMitBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [lowBackGroundView addSubview:_subMitBtn];
    
    //全局 scrollerView
    _myScrollView = CREATE_WITH_FRAME_OF(UIScrollView, [self.view.ufo fx:0 oy:self.navigationAndStatusBarHeight],
                                       [self.view.ubo ow:SCREEN_WIDTH fh:1.0 oh:-self.navigationAndStatusBarHeight-lowBackGroundView.ubo.height]);
    [self.view addSubview:_myScrollView];
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textViewResignFirstResponder)];
    [_myScrollView addGestureRecognizer:tap];
    
    //订单基本信息 View
    SNReturnGoodsView * basicView = [[SNReturnGoodsView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 80) sn:self.sn createTime:self.timeStr receiver:self.receiverName isReturns:self.isReturns ostatus:self.ostatus];
    [_myScrollView addSubview:basicView];
    
    //商品信息 View
    SNAddCommentsView * goodsView = [[SNAddCommentsView alloc] initWithFrame:CGRectMake(0, basicView.ufo.yy, SCREEN_WIDTH, 84) model:self.listModel type:GoodsViewTypeReturnGoods];
    [_myScrollView addSubview:goodsView];
    
    // textView 和 左边红星的背景图
    UIView * textBackGroundView = CREATE_WITH_FRAME_OF(UIView, [goodsView.ufo ux:24 fy:1.0 oy:20],
                                                       [goodsView.ubo ow:SCREEN_WIDTH-UF(48) oh:150]);
    textBackGroundView.layer.cornerRadius = 2;
    textBackGroundView.layer.borderWidth = UP(1);
    textBackGroundView.layer.borderColor = [XCommon hexStringToColor:kColor_gray_line].CGColor;
    textBackGroundView.backgroundColor = [XCommon hexStringToColor:kColor_lightGray_backGround];
    [_myScrollView addSubview:textBackGroundView];
    
    //红星 lable
    UILabel * redStartLabel = CREATE_WITH_FRAME_OF(UILabel, [textBackGroundView.ubo ox:10 fy:0],
                                                   [goodsView.ubo ow:10 oh:36]);
    redStartLabel.text = @" *";
    redStartLabel.textColor = [UIColor redColor];
    redStartLabel.backgroundColor = [XCommon hexStringToColor:kColor_lightGray_backGround];
    [textBackGroundView addSubview:redStartLabel];
    
    UILabel * tishiLabel = CREATE_WITH_FRAME_OF(UILabel, [textBackGroundView.ubo ox:30 fy:0],
                                                [goodsView.ubo ow:60 oh:30]);
    tishiLabel.text = @"我要售后:";
    tishiLabel.textColor = [UIColor blackColor];
    tishiLabel.font = JKAppGlobleFontSmallTagText;
    [textBackGroundView addSubview:tishiLabel];
    
    //输入框 textView
    _textView = CREATE_WITH_FRAME_OF(UITextView, [tishiLabel.ufo fx:1.0 fy:0],
                                     [textBackGroundView.ubo fw:1.0 ow:-tishiLabel.ufo.xx-3 fh:1.0]);
    _textView.textColor = [XCommon hexStringToColor:kColor_l_light_gray_text];
    _textView.backgroundColor = [XCommon hexStringToColor:kColor_lightGray_backGround];
    _textView.delegate = self;
    _textView.font = JKAppGlobleFontSmallTagText;
    [textBackGroundView addSubview:_textView];
    
    //提示语 label
    _placeLabel = [[UILabel alloc] init];
    NSString * placeStr = @"买错了,不想要,质量问题您可以通通告诉我们,我们都会为您解决,切记留下您的手机号TEL,方便我们服务您。";
    CGFloat placeLabelHeight = [XCommon heightForString:placeStr fontSize:13 andWidth:_textView.ubo.width-10];
    _placeLabel.frame = CGRectOf([_textView.ufo fx:0 ox:5 fy:0 oy:8],
                                 [_textView.ubo fw:1.0 ow:-13 oh:placeLabelHeight]);
    _placeLabel.userInteractionEnabled = NO; //取消其与用户交互的权限
    _placeLabel.numberOfLines = 0;
    NSMutableAttributedString * placeAttributedStr = [[NSMutableAttributedString alloc] initWithString:placeStr];
    [placeAttributedStr addAttributes:@{NSFontAttributeName:JKAppGlobleFontSmallTagText,NSForegroundColorAttributeName:[XCommon hexStringToColor:kColor_s_light_gray_text]} range:NSMakeRange(0, placeStr.length)];
    [placeAttributedStr addAttributes:@{NSFontAttributeName:JKAppGlobleFontSmallTagText,NSForegroundColorAttributeName:[UIColor orangeColor]} range:NSMakeRange(37, 6)];
    _placeLabel.attributedText = placeAttributedStr;
    [textBackGroundView addSubview:_placeLabel];
    
    //添加图片 button
    _addImgsBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _addImgsBtn.frame = CGRectOf([textBackGroundView.ufo fx:0 fy:1.0 oy:15],
                                 [textBackGroundView.ubo ow:65 oh:65]);
    [_addImgsBtn setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"addCommentPic@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [_addImgsBtn addTarget:self action:@selector(addImgBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_myScrollView addSubview:_addImgsBtn];
    
    _myScrollView.contentSize = CGSizeMake(SCREEN_WIDTH, _addImgsBtn.ufo.yy+10);
}

#pragma mark - 点击了 scrollerView 收起键盘
- (void)textViewResignFirstResponder
{
    [_textView resignFirstResponder];
}

#pragma mark - 点击了 添加图片 按钮
- (void)addImgBtnClick
{
    [self.textView resignFirstResponder];
    
    if (self.picBackGroundViewArray.count < 3) {//最多添加3张图片
        HDActionSheetView *actv = [[HDActionSheetView alloc] initWithTitle:nil cancelButtonTitle:@"取消" otherButtonTitles:@"拍照",@"从相册选",nil];
        actv.syActionSheetActionBlock = ^(UIButton *actionBtn){
            
            if (actionBtn.tag == kBtnCaccleTag + 1)
            {
                SYLog(@"%@",actionBtn.titleLabel.text);
                [self takePhoto];
                
            }
            else if (actionBtn.tag == kBtnCaccleTag + 2)
            {
                SYLog(@"%@",actionBtn.titleLabel.text);
                [self localPhoto];
            }
        };
        [actv showSYActionSheet];
    } else {
        _addImgsBtn.userInteractionEnabled = NO;
    }
}

#pragma mark - 打开照相机
-(void)takePhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可否编辑
        picker.allowsEditing = NO;
        picker.sourceType = sourceType;
        
        [self presentViewController:picker animated:NO completion:nil];
    } else {
        
    }
}
#pragma mark - 打开相册
-(void)localPhoto
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可否编辑
    picker.allowsEditing = NO;
    [self presentViewController:picker animated:NO completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate 保存图片
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage * image = [info[@"UIImagePickerControllerEditedImage"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    if (!image) {
        image = [info[@"UIImagePickerControllerOriginalImage"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    }
    
    [self createImgViewWithImg:image];
    
    [picker dismissViewControllerAnimated:NO completion:nil];
}

#pragma mark - 创建图片视图
- (void)createImgViewWithImg:(UIImage *)img;
{
    //图片背景图
    UIView * picBackGroundView = [[UIView alloc] init];
    picBackGroundView.frame = _addImgsBtn.frame;
    [self.myScrollView addSubview:picBackGroundView];
    [self.picBackGroundViewArray addObject:picBackGroundView];
    picBackGroundView.tag = [self.picBackGroundViewArray indexOfObject:picBackGroundView]+1001;
    
    //需要上传的图片(最多三张)
    UIImageView * picView = [[UIImageView alloc] initWithFrame:picBackGroundView.bounds];
    picView.layer.masksToBounds = YES;
    picView.layer.cornerRadius = 4;
    picView.layer.borderColor = [XCommon hexStringToColor:kColor_gray_line].CGColor;
    picView.layer.borderWidth = UP(1);
    picView.image = img;
    picView.contentMode = UIViewContentModeScaleAspectFit;
    [picBackGroundView addSubview:picView];
    
    //舍弃图片的按钮
    UIButton * abandonBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    abandonBtn.frame = CGRectOf([picBackGroundView.ubo fx:1.0 ox:-15 fy:0 oy:-15],
                                CGSizeMake(30, 30));
    abandonBtn.imageEdgeInsets = UIEdgeInsetsMake(6, 6, 6, 6);
    [abandonBtn setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"abandon@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [abandonBtn addTarget:self action:@selector(abandonBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [picBackGroundView addSubview:abandonBtn];
    abandonBtn.tag =[self.picBackGroundViewArray indexOfObject:picBackGroundView]+1;
    [abandonBtn bringSubviewToFront:picBackGroundView];
    
    _addImgsBtn.frame = CGRectOf([picBackGroundView.ufo fx:1.0 ux:24 fy:0],
                                 picBackGroundView.ubo.size);
}

#pragma mark - 点击了 图片上的 x 号 : 舍弃图片
- (void)abandonBtnClick:(UIButton *)btn
{
    UIView * view = [self.view viewWithTag:btn.tag + 1000];
    
    //判断移除的那张图片的右面是不是还有图片
    if (self.picBackGroundViewArray.count > btn.tag) {//有
        //移除的那张图片的右面的图片左移
        
        CGRect willFrame = view.frame;
        for (int i = (int)btn.tag; i < self.picBackGroundViewArray.count; i++) {
            
            UIView * nextView = [self.view viewWithTag:i+1000+1];
            CGRect tempFrame = nextView.frame;
            nextView.frame = willFrame;
            willFrame = tempFrame;
        }
        
        //将 _addImgsBtn 左移
        UIView * lastPicBackGroundView = [self.picBackGroundViewArray lastObject];
        _addImgsBtn.frame = CGRectOf([lastPicBackGroundView.ufo fx:1.0 ux:24 fy:0],
                                     lastPicBackGroundView.ubo.size);
        
    } else {//没有
        //直接将 _addImgsBtn 左移
        _addImgsBtn.frame = view.frame;
    }
    
    //将点击的图片从屏幕中移除
    [view removeFromSuperview];
    //将图片从 self.picBackGroundViewArray 数组中移除
    [self.picBackGroundViewArray removeObjectAtIndex:btn.tag-1];
    
    //改变控件的 tag 值
    for (UIView * subView in self.picBackGroundViewArray) {
        subView.tag = [self.picBackGroundViewArray indexOfObject:subView]+1001;
        
        for (UIView * buttonView in subView.subviews) {
            if ([buttonView isKindOfClass:[UIButton class]]) {
                buttonView.tag = [self.picBackGroundViewArray indexOfObject:subView]+1;
            }
        }
        
    }
}


#pragma mark - 点击了 提交申请 按钮
- (void)subMitBtnClick
{
    if (self.textView.text.length == 0) {//没有填写需要售后的原因
        [MyToast showDefaultBottonWithText:@"请填写需要售后的原因..."];
        return;
    }
    
    [MBProgressHUD showMBProgressHUBOnWindowsWithMessage:@"提交申请中..."];
    
    self.upLoadPicManager = [SNReturnGoodsUpLoadPicDataManager shareManager];
    
    if (self.picBackGroundViewArray.count > 0) {//有图片
        [self.picArray removeAllObjects];
        
        self.imgResut = [[SNReturnGoodsUploadImgHttpResult alloc] initWithTarget:self action:@selector(loadUpLoadImgData:)];
        for (UIView * subView in self.picBackGroundViewArray) {
            for (UIView * imageView in subView.subviews) {
                if ([imageView isKindOfClass:[UIImageView class]]) {
                    UIImageView * imgView = (UIImageView *)imageView;
                    [self.picArray addObject:imgView.image];
                }
            }
        }
        
        //将图片上传
        for (UIImage * image in self.picArray) {
            NSData * imgData = [SNTool imageMaxWidthOrHeight720DataWithImage:image];
            NSString * imgType = [SNTool typeForImageData:imgData];
            
            NSDictionary * params = @{@"product_id":self.listModel.product_id,
                                      @"name" : @"image",
                                      @"fileName" : [NSString stringWithFormat:@"%@%d",self.listModel.product_id,(int)[self.picArray indexOfObject:image]+1],
                                      @"mimeType" : imgType};
            
            [self.upLoadPicManager returnGoodsPicWithResult:self.imgResut params:params imageData:imgData];
        }
        
    } else {
        [self upLoadText];
    }
}

#pragma mark - 上传图片的回调
- (void)loadUpLoadImgData:(SNReturnGoodsUploadImgHttpResult *)result
{
    if (result.success) {
        DLog(@"上传图片成功 ---- %@",result.picsArray);
        
        if (result.picsArray.count == self.picBackGroundViewArray.count) {//图片全部上传成功之后进行文字上传
            [self upLoadText];
        }
        
    } else {
        DLog(@"上传图片失败");
        [MBProgressHUD showToastWithMessage:@"上传图片失败,请重试..." toView:self.view];
    }
}

- (void)upLoadText
{
    self.manager = [SNReturnGoodsDataManager shareManager];
    self.textResult = [[SNReturnGoodsUploadTextHttpResult alloc] initWithTarget:self action:@selector(loadUpLoadTextData:)];
    
    NSString * pics = [self stringWithpicArray:self.imgResut.picsArray];
    
    [self.manager returnGoodsTextWithResult:self.textResult sn:self.sn returnsfor:@"2" productIDs:self.listModel.product_id contacts:self.receiverPhoneNum returnsReason:self.textView.text pics:pics];
}

- (NSString *)stringWithpicArray:(NSArray *)picStrArray
{
    NSMutableString * mutabString = [[NSMutableString alloc] init];
    
    if (picStrArray.count == 0) {
        [mutabString appendString:@""];
    } else {
        if (picStrArray.count == 1) {//只有一条不用拼接 '|'
            mutabString = [NSMutableString stringWithString:[picStrArray lastObject]];
        } else {
            for (NSString * string in picStrArray) {
                [mutabString appendString:[NSString stringWithFormat:@"%@|",string]];
            }
            DLog(@"%@",mutabString);
            [mutabString deleteCharactersInRange:NSMakeRange(mutabString.length-1, 1)];
            DLog(@"%@",mutabString);
        }
    }
    
    return mutabString;
}

- (void)loadUpLoadTextData:(SNReturnGoodsUploadTextHttpResult *)result
{
    if (result.success) {
        DLog(@"申请售后成功");
        
        [MBProgressHUD showToastWithMessage:@"提交申请成功" toView:self.view];
        [self performSelector:@selector(selfPopViewController) withObject:nil afterDelay:1];
    } else {
        DLog(@"申请售后失败");
        [MBProgressHUD showToastWithMessage:@"提交申请失败" toView:self.view];
    }
}

- (void)selfPopViewController
{
    [MBProgressHUD dismissMBProgressHUBOnWindows];
    
    [self.navigationController popViewControllerAnimated:YES];
    
//    if ([self.popToVCNameStr isEqualToString:@"SNReturnGoodsRepetitiousViewController"]) {
//        [self.navigationController popViewControllerAnimated:YES];
//    } else if ([self.popToVCNameStr isEqualToString:@"SNOrderFormDetailViewController"]) {
//        SNReturnGoodsRepetitiousViewController * returnGoodsRepetitionsVC = [[SNReturnGoodsRepetitiousViewController alloc] init];
//        returnGoodsRepetitionsVC.sn = self.sn;
//        returnGoodsRepetitionsVC.productId = self.listModel.product_id;
//        returnGoodsRepetitionsVC.receiverPhoneNum = self.receiverPhoneNum;
//        returnGoodsRepetitionsVC.listModel = self.listModel;
//        [self.navigationController pushViewController:returnGoodsRepetitionsVC animated:YES];
//    }
}

- (void)textViewDidChange:(UITextView *)textView
{
    if (_textView.text.length > 0) {
        _placeLabel.hidden = YES;
    } else if (_textView.text.length == 0) {
        _placeLabel.hidden = NO;
    }
}

- (void)keyBoardAppear:(NSNotification*)aNotification
{
    _kbTime = [aNotification.userInfo[@"UIKeyboardAnimationDurationUserInfoKey"] floatValue];
    CGFloat kbHeight = [[aNotification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    
    _myScrollView.contentInset = UIEdgeInsetsMake(0, 0, kbHeight, 0);
    [UIView animateWithDuration:_kbTime animations:^{
        _myScrollView.contentOffset = CGPointMake(0, _textView.superview.ufo.y-_textView.superview.ufo.x);
    }];
}

- (void)keyBoardHidden:(NSNotification*)aNotification
{
    _myScrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    [UIView animateWithDuration:_kbTime animations:^{
        _myScrollView.contentOffset = CGPointMake(0, 0);
    }];
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView
{
    UIImage * subMitBtnBackGroundImg;
    if (_textView.text.length > 0) {
        subMitBtnBackGroundImg = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"btnBackGround@2x" ofType:@"png"]];
        subMitBtnBackGroundImg = [subMitBtnBackGroundImg resizableImageWithCapInsets:UIEdgeInsetsMake(UP(6), UP(6), UP(6), UP(6)) resizingMode:UIImageResizingModeStretch];
    } else {
        subMitBtnBackGroundImg = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"btnBackGround_gray@2x" ofType:@"png"]];
        subMitBtnBackGroundImg = [subMitBtnBackGroundImg resizableImageWithCapInsets:UIEdgeInsetsMake(UP(6), UP(6), UP(6), UP(6)) resizingMode:UIImageResizingModeStretch];
    }
    [_subMitBtn setBackgroundImage:subMitBtnBackGroundImg forState:UIControlStateNormal];
    return YES;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
